class IterationsController < ApplicationController
  # GET /iterations
  # GET /iterations.xml
  def index
    @iterations = Iteration.find(:all, :order => 'start_date desc')

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @iterations.to_xml(:methods => [:daily_load,:work_units_real, :agile_tasks_number]) }
    end
  end

  # GET /iterations/1
  # GET /iterations/1.xml
  def show
    @iteration = Iteration.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @iteration.to_xml(:methods => [:daily_load,:work_units_real, :agile_tasks_number]) }
    end
  end

  # GET /iterations/new
  # GET /iterations/new.xml
  def new
    @iteration = Iteration.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @iteration.to_xml(:methods => [:daily_load,:work_units_real, :agile_tasks_number]) }
    end
  end

  # GET /iterations/1/edit
  def edit
    @iteration = Iteration.find(params[:id])
  end

  # POST /iterations
  # POST /iterations.xml
  def create
    @iteration = Iteration.new(params[:iteration])

    respond_to do |format|
      if developer?
        if @iteration.save
          flash[:notice] = 'Iteration was successfully created.'
          format.html { redirect_to(@iteration) }
          format.xml  { render :xml => @iteration, :status => :created, :location => @iteration }
        else
          format.html { render :action => "new" }
          format.xml  { render :xml => @iteration.errors, :status => :unprocessable_entity }
        end
      else
       format.xml { render :xml => XML_ERRORS[:not_authorized] }
      end
    end
  end

  # PUT /iterations/1
  # PUT /iterations/1.xml
  def update
    @iteration = Iteration.find(params[:id])

    respond_to do |format|
      if developer?
        if @iteration.update_attributes(params[:iteration])
          flash[:notice] = 'Iteration was successfully updated.'
          format.html { redirect_to(@iteration) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @iteration.errors, :status => :unprocessable_entity }
        end
      else
        format.xml { render :xml => XML_ERRORS[:not_authorized]}
      end
    end
  end

  # DELETE /iterations/1
  # DELETE /iterations/1.xml
  def destroy
    @iteration = Iteration.find(params[:id])
    begin
      respond_to do |format|
        if developer?
          @iteration.destroy
          format.html { redirect_to(iterations_url) }
          format.xml  { head :ok }
        else
          format.xml { render :xml => XML_ERRORS[:not_authorized]}
        end
      end
    rescue ActiveRecord::StatementInvalid 
      respond_to do |format| 
        format.xml  { render  :xml => XML_ERRORS[:foreign_key_problem] } 
      end
    end      
  end
end
